<template>
  <div class="app-container">
    <!-- 动态查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item
        v-for="field in queryFields"
        :key="field.fieldName"
        :label="field.fieldLabel"
        :prop="field.fieldName"
      >
        <!-- 文本输入 -->
        <el-input
          v-if="field.fieldType === 'text'"
          v-model="queryParams[field.fieldName]"
          :placeholder="'请输入' + field.fieldLabel"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px;"
        />
        <!-- 字典选择 -->
        <el-select
          v-else-if="field.fieldType === 'dict'"
          v-model="queryParams[field.fieldName]"
          :placeholder="'请选择' + field.fieldLabel"
          clearable
          style="width: 200px;"
        >
          <el-option
            v-for="dict in dict.type[field.dictType]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <!-- 日期范围 -->
        <el-date-picker
          v-else-if="field.fieldType === 'date' && field.queryType === 'BETWEEN'"
          v-model="dateRange[field.fieldName]"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px;"
        />
        <!-- 单个日期 -->
        <el-date-picker
          v-else-if="field.fieldType === 'date'"
          v-model="queryParams[field.fieldName]"
          type="date"
          :placeholder="'选择' + field.fieldLabel"
          value-format="yyyy-MM-dd"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['report:saleSummary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 汇总统计卡片 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="text-align: center;">
            <div style="font-size: 14px; color: #909399;">运单总数</div>
            <div style="font-size: 24px; font-weight: bold; color: #409EFF; margin-top: 10px;">
              {{ summaryData.totalCount || 0 }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="text-align: center;">
            <div style="font-size: 14px; color: #909399;">总结算量</div>
            <div style="font-size: 24px; font-weight: bold; color: #67C23A; margin-top: 10px;">
              {{ summaryData.totalQty ? parseFloat(summaryData.totalQty).toFixed(2) : '0.00' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="text-align: center;">
            <div style="font-size: 14px; color: #909399;">总结算金额</div>
            <div style="font-size: 24px; font-weight: bold; color: #E6A23C; margin-top: 10px;">
              {{ summaryData.totalAmount ? parseFloat(summaryData.totalAmount).toFixed(2) : '0.00' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div style="text-align: center;">
            <div style="font-size: 14px; color: #909399;">平均单价</div>
            <div style="font-size: 24px; font-weight: bold; color: #F56C6C; margin-top: 10px;">
              {{ summaryData.avgPrice ? parseFloat(summaryData.avgPrice).toFixed(2) : '0.00' }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 动态数据表格 -->
    <el-table v-loading="loading" :data="reportList" border show-summary :summary-method="getSummaries">
      <el-table-column
        v-for="field in listFields"
        :key="field.fieldName"
        :label="field.fieldLabel"
        :align="field.align"
        :prop="field.fieldName"
        :width="field.columnWidth"
      >
        <template slot-scope="scope">
          <!-- 数字类型 -->
          <span v-if="field.fieldType === 'number'">
            {{ scope.row[field.fieldName] ? parseFloat(scope.row[field.fieldName]).toFixed(2) : '0.00' }}
          </span>
          <!-- 其他类型 -->
          <span v-else>{{ scope.row[field.fieldName] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listSaleSummary, exportSaleSummary } from "@/api/report/saleSummary"
import { getListFieldsByCode, getQueryFieldsByCode } from "@/api/report/config"

export default {
  name: "SaleSummaryReport",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表数据
      reportList: [],
      // 列表字段配置
      listFields: [],
      // 查询字段配置
      queryFields: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 日期范围
      dateRange: {},
      // 汇总数据
      summaryData: {
        totalCount: 0,
        totalQty: 0,
        totalAmount: 0,
        avgPrice: 0
      }
    };
  },
  created() {
    this.loadFieldConfig();
  },
  methods: {
    /** 加载字段配置 */
    loadFieldConfig() {
      // 加载列表字段配置
      getListFieldsByCode('sale_summary').then(response => {
        this.listFields = response.data;
      });
      
      // 加载查询字段配置
      getQueryFieldsByCode('sale_summary').then(response => {
        this.queryFields = response.data;
        this.getList();
      });
    },
    /** 查询报表列表 */
    getList() {
      this.loading = true;
      
      // 处理查询参数
      const params = { ...this.queryParams };
      
      // 处理日期范围
      this.queryFields.forEach(field => {
        if (field.fieldType === 'date' && field.queryType === 'BETWEEN') {
          if (this.dateRange[field.fieldName] && this.dateRange[field.fieldName].length === 2) {
            params[field.fieldName + 'Start'] = this.dateRange[field.fieldName][0];
            params[field.fieldName + 'End'] = this.dateRange[field.fieldName][1];
          }
        }
      });
      
      listSaleSummary(params).then(response => {
        this.reportList = response.rows;
        this.total = response.total;
        this.calculateSummary();
        this.loading = false;
      });
    },
    /** 计算汇总数据 */
    calculateSummary() {
      if (this.reportList && this.reportList.length > 0) {
        let totalCount = 0;
        let totalQty = 0;
        let totalAmount = 0;
        
        this.reportList.forEach(item => {
          totalCount += parseInt(item.totalCount || 0);
          totalQty += parseFloat(item.totalQty || 0);
          totalAmount += parseFloat(item.totalAmount || 0);
        });
        
        this.summaryData = {
          totalCount: totalCount,
          totalQty: totalQty,
          totalAmount: totalAmount,
          avgPrice: totalQty > 0 ? (totalAmount / totalQty) : 0
        };
      } else {
        this.summaryData = {
          totalCount: 0,
          totalQty: 0,
          totalAmount: 0,
          avgPrice: 0
        };
      }
    },
    /** 表格合计行 */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        
        // 查找对应的字段配置
        const field = this.listFields.find(f => f.fieldName === column.property);
        
        // 数字类型字段进行求和
        if (field && field.fieldType === 'number') {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = parseFloat(sums[index]).toFixed(2);
          } else {
            sums[index] = '-';
          }
        } else {
          sums[index] = '-';
        }
      });
      
      return sums;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      };
      this.dateRange = {};
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有销售汇总报表数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        
        // 处理查询参数
        const params = { ...this.queryParams };
        delete params.pageNum;
        delete params.pageSize;
        
        // 处理日期范围
        this.queryFields.forEach(field => {
          if (field.fieldType === 'date' && field.queryType === 'BETWEEN') {
            if (this.dateRange[field.fieldName] && this.dateRange[field.fieldName].length === 2) {
              params[field.fieldName + 'Start'] = this.dateRange[field.fieldName][0];
              params[field.fieldName + 'End'] = this.dateRange[field.fieldName][1];
            }
          }
        });
        
        return exportSaleSummary(params);
      }).then(response => {
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '销售汇总报表_' + new Date().getTime() + '.xlsx');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
